﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace Milink.SaiKe.Remote
{
    public static class SaiKeUtility
    {
        public const int LengthBytePos = 2;
        public const int VerNoBytePos = 4;
        public const int CmdBytePos = 5;
        public const int BodyBytePos = 6;

        #region getQueryParam
        public static Dictionary<string, string> getQueryParam(string queryString)
        {
            if (string.IsNullOrWhiteSpace(queryString))
                return new Dictionary<string, string>();

            string[] pairs = HttpUtility.UrlDecode(queryString).Trim().Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries);

            if (pairs.Length == 0)
                return new Dictionary<string, string>();
            else
                return pairs.Where(s => s.IndexOf("=") > 0).Select(s =>
                {
                    int idx = s.IndexOf('=');
                    return new KeyValuePair<string, string>(Uri.UnescapeDataString(s.Substring(0, idx)), Uri.UnescapeDataString(s.Substring(idx + 1)));
                }).ToDictionary(x => x.Key, x => x.Value);
        }
        #endregion

        #region leftMerge
        public static Dictionary<string, string> leftMerge(this Dictionary<string, string>  leftDict, Dictionary<string, string> rightDict)
        {
            foreach (KeyValuePair<string, string> pair in rightDict)
            {
                if (!leftDict.ContainsKey(pair.Key))
                {
                    leftDict.Add(pair.Key, pair.Value);
                }
            }
            return leftDict;
        }
        #endregion

        #region sendToApp
        private const string param = "cmd={0}&data={1}";
        public static void sendToApp(string url, string cmd, string entity)
        {
            if (!string.IsNullOrWhiteSpace(url))
            {
                string body = string.Format(param, cmd, entity);
                HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
                HttpWebResponse httpResponse = null;
                try
                {
                    httpRequest.Method = "POST";
                    httpRequest.ContentType = "application/x-www-form-urlencoded";
                    byte[] data = Encoding.UTF8.GetBytes(body);
                    httpRequest.ContentLength = data.Length;
                    httpRequest.GetRequestStream().Write(data, 0, data.Length);
                    httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                }
                catch
                {

                }
                finally
                {
                    if (httpResponse != null) httpResponse.Close();
                    httpRequest.Abort();
                }
            }
        }
        #endregion
    }
}
